package com.jumi.microservice.service.logistics;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.dto.logistics.*;
import com.jumi.microservice.entity.OrderGoods;
import com.jumi.microservice.entity.UserOrder;
import com.jumi.microservice.enumerate.ExamineEnum;
import com.jumi.microservice.enumerate.OrderStatusEnum;
import com.jumi.microservice.enumerate.OrderTypeEnum;
import com.jumi.microservice.mapper.OrderGoodsMapper;
import com.jumi.microservice.mapper.UserOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * @Classname AutoSpiltService
 * @Description TODO
 * @Date 2020/8/8 15:10
 */
@Service
public class OrderRelatedService {

    @Resource
    OrderGoodsMapper orderGoodsMapper;
    @Resource
    UserOrderMapper userOrderMapper;

    private static final Logger log = LoggerFactory.getLogger(OrderRelatedService.class);
    /**
     * 获取订单下面所有商品
     * @param userOrder
     * @return
     */
    public List<GoodsEntity> getOrderGoods(UserOrder userOrder){
        List<GoodsEntity> result = new ArrayList<>();
        QueryWrapper<OrderGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0).eq("order_id", userOrder.getId());
        List<OrderGoods> list =  orderGoodsMapper.selectList(queryWrapper);
        if(list.stream().map(OrderGoods::getVerifyStatus).collect(Collectors.toList()).contains((byte)1)){
            return result;
        }
        for (OrderGoods g:list){
            GoodsEntity goodsEntity = new GoodsEntity();
            BeanUtils.copyProperties(g,goodsEntity);
            goodsEntity.setOrderNo(userOrder.getOrderNo());
            goodsEntity.setOrderCreateTime(g.getCreateTime());
            goodsEntity.setReceiverAddress(userOrder.getReceiverAddress());
            goodsEntity.setReceiverName(userOrder.getReceiverName());
            goodsEntity.setReceiverPhone(userOrder.getReceiverPhone());
            goodsEntity.setBuyerId(userOrder.getBuyerId());
            result.add(goodsEntity);
        }
        return result;
    }

    /**
     * 根据订单编号获取该订单信息
     * @return
     */
    public LogisticsPackage getOrderPackage(OrderInfoRequest request){
        QueryWrapper<UserOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0)
                .eq("order_type", OrderTypeEnum.USER_CREATE.getCode())
                .and(q->q.eq("order_status", OrderStatusEnum.READY_TO_SHIP.getCode()).or()
                        .eq("order_status",OrderStatusEnum.READY_TO_RECEIVE.getCode()).isNull("confirm_time"));
        if(request.getOrderId()!=null){
            queryWrapper.eq("id",request.getOrderId());
        }else if(request.getOrderNo()!=null){
            queryWrapper.eq("order_no",request.getOrderNo());
        }
        UserOrder userOrder = userOrderMapper.selectOne(queryWrapper);
        if(userOrder==null){
            log.info("该订单不满足待拆单条件 [{}],等待2秒重新查询",request.getOrderNo()==null?request.getOrderId():request.getOrderNo());
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            userOrder = userOrderMapper.selectOne(queryWrapper);
            if(userOrder==null){
                log.info("该订单不满足待拆单条件 [{}]",request.getOrderNo()==null?request.getOrderId():request.getOrderNo());
                return null;
            }
        }
        log.info("查询到的待拆单订单数据 [{}]", JSON.toJSONString(userOrder));
        List<GoodsEntity> goodsEntityList = getOrderGoods(userOrder);
        if(goodsEntityList.isEmpty()){
            log.info("订单 [{}] ,包含待审核商品",userOrder.getOrderNo());
            return null;
        }
        LogisticsPackage logisticsPackage = new LogisticsPackage();
        BeanUtils.copyProperties(userOrder,logisticsPackage);
        logisticsPackage.setList(goodsEntityList);
        return logisticsPackage;
    }

}
